#include "stdafx.h"
#include "AutoCombo.h"

namespace cm {
namespace Windows {

BOOL CComboBoxAutoComplete::PreTranslateMessage(MSG* pMsg)
{
	// Need to check for backspace/delete. These will modify the text in
	// the edit box, causing the auto complete to just add back the text
	// the user has just tried to delete.

	HWND hEdit = ::FindWindowEx(m_hWnd,NULL,_T("Edit"),NULL);

	if (pMsg->hwnd == hEdit)
	{
		if (pMsg->message == WM_KEYDOWN)
		{
			m_bAutoComplete = true;

			int nVirtKey = (int)pMsg->wParam;
			if (nVirtKey == VK_DELETE || nVirtKey == VK_BACK)
			{
				m_bAutoComplete = false;
			}
			if (nVirtKey == VK_RETURN)
			{
				CString str;
				GetWindowText(str);
				if (str != _T(""))
				{			
					GetParent().PostMessage(m_NotificationMsg,0,(LPARAM)FindStringExact(-1,str));
					return TRUE;
				}
			}
		}
	}

	return FALSE;
}

LRESULT CComboBoxAutoComplete::OnEditUpdate(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL bHandled)
{
	// if we are not to auto update the text, get outta here
	if (!m_bAutoComplete) 
	{
		bHandled = FALSE;
		return 0;
	}

	// Get the text in the edit box
	CString str;
	GetWindowText(str);
	int nLength = str.GetLength();

	// Currently selected range
	DWORD dwCurSel = GetEditSel();
	WORD dStart = LOWORD(dwCurSel);
	WORD dEnd   = HIWORD(dwCurSel);

	// Search for, and select in, and string in the combo box that is prefixed
	// by the text in the edit box
	if (SelectString(-1, str) == CB_ERR)
	{
	  SetWindowText(str);		// No text selected, so restore what was there before
	  if (dwCurSel != CB_ERR)
		SetEditSel(dStart, dEnd);	//restore cursor postion
	}

	// Set the text selection as the additional text that we have added
	if (dEnd < nLength && dwCurSel != CB_ERR)
	  SetEditSel(dStart, dEnd);
	else
	  SetEditSel(nLength, -1);

	return 0;
}

}}